<script setup lang="ts">
import { ref, onMounted, reactive, nextTick, computed, watch } from "vue";
import { useECharts } from "@/hooks/useECharts";
import * as echarts from "echarts";
import type { EChartsOption } from "echarts";
import { useRouter } from "vue-router";
import { getStatisticsOverview, getDailyStatistics, type StatisticsInfo, type DailyLoanStatistics } from "@/api/statistics";
import { ElMessage } from "element-plus";
import { formatDate } from "@/utils/format";

// 路由实例
const router = useRouter();

// 数据加载状态
const loading = ref(false);
const chartLoading = ref(false);

// 统计数据
const statisticsData = ref<StatisticsInfo>({
  total_loan_amount: 0,
  self_loan_amount: 0,
  assist_loan_amount: 0,
  month_loan_amount: 0,
  month_self_loan_amount: 0,
  month_assist_loan_amount: 0,
  today_loan_amount: 0,
  total_pending_loan: 0,
  total_pending_repay: 0,
  total_settlement: 0,
  total_brokers: 0
});

// 图表数据
const chartData = ref({
  list: [] as DailyLoanStatistics[],
  total_amount: 0,
  target_amount: 0,
  investment_rate: 0,
  total_charge: 0,
  completed_charge: 0,
  charge_rate: 0
});

// 计算投放完成率和收费完成率百分比
const investmentRateText = computed(() => `${Math.round(chartData.value.investment_rate * 100)}%`);
const chargeRateText = computed(() => `${Math.round(chartData.value.charge_rate * 100)}%`);

// 图表相关
const chartRef = ref(null);
let chartInstance = null;

// 日期筛选
const dateRange = ref([]);
const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 格式化金额函数
const formatAmount = (amount: number) => {
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

// 跳转到费用结算页面
const goToFeeSettlement = () => {
  router.push('/data-statistics/fee-settlement');
};

// 加载统计数据
const loadStatisticsData = async () => {
  loading.value = true;
  try {
    const res = await getStatisticsOverview();
    if (res.success) {
      statisticsData.value = res.data;
    } else {
      ElMessage.error(res.msg || '获取统计数据失败');
    }
  } catch (error) {
    console.error('获取统计数据出错:', error);
    ElMessage.error('获取统计数据失败');
  } finally {
    loading.value = false;
  }
};

// 加载图表数据
const loadChartData = async () => {
  chartLoading.value = true;
  try {
    // 准备请求参数
    const params: Record<string, any> = {};
    if (dateRange.value && dateRange.value.length === 2) {
      params.start_date = formatDate(dateRange.value[0], 'YYYY-MM-DD');
      params.end_date = formatDate(dateRange.value[1], 'YYYY-MM-DD');
    }

    const res = await getDailyStatistics(params);
    if (res.success) {
      chartData.value = res.data;
      updateChart();
    } else {
      ElMessage.error(res.msg || '获取图表数据失败');
    }
  } catch (error) {
    console.error('获取图表数据出错:', error);
    ElMessage.error('获取图表数据失败');
  } finally {
    chartLoading.value = false;
  }
};

onMounted(async () => {
  // 加载统计数据
  await loadStatisticsData();

  // 加载图表数据
  await loadChartData();

  // 等待DOM渲染完成
  await nextTick();
  // 初始化图表
  initChart();
});

// 监听日期变化
watch(dateRange, () => {
  if (dateRange.value && dateRange.value.length === 2) {
    loadChartData();
  }
});

// 初始化图表
function initChart() {
  if (chartRef.value) {
    // 销毁可能存在的旧实例
    if (chartInstance) {
      chartInstance.dispose();
    }

    // 手动创建echarts实例
    chartInstance = echarts.init(chartRef.value);

    // 确保正确渲染
    window.addEventListener('resize', () => {
      if (chartInstance) chartInstance.resize();
    });

    // 初始显示图表
    updateChart();
  }
}

// 更新图表
function updateChart() {
  if (!chartRef.value || !chartInstance) return;

  const xAxisData = chartData.value.list.map(item => item.date);
  const seriesData = chartData.value.list.map(item => item.loan_amount);

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      },
      formatter: function (params) {
        const item = params[0];
        return `${item.name}: ${item.value.toLocaleString('zh-CN', {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2
        })}元`;
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "8%",
      top: "8%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: xAxisData,
      axisLabel: {
        interval: 'auto',
        formatter: function (value) {
          // 仅显示日期部分
          return value.substring(5); // 仅显示月-日部分，如 "05-21"
        }
      }
    },
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: function (value) {
          if (value >= 10000) {
            return (value / 10000).toFixed(1) + '万';
          }
          return value;
        }
      }
    },
    series: [
      {
        name: "放款金额",
        type: "line",
        data: seriesData,
        color: "#67C23A",
        smooth: true,
        symbolSize: 8,
        emphasis: {
          itemStyle: {
            borderWidth: 3
          }
        },
        lineStyle: {
          width: 3
        }
      }
    ]
  };

  chartInstance.setOption(option);
}

// 处理日期变化
function handleDateChange() {
  if (dateRange.value && dateRange.value.length === 2) {
    loadChartData();
  }
}
</script>

<template>
  <div class="statistics-overview">
    <div class="data-cards" v-loading="loading">
      <!-- 第一行卡片 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="data-card" shadow="never">
            <div class="card-title">
              <span>放款总额</span>
              <el-tooltip content="累计已放款金额" placement="top">
                <el-icon><i-ep-question-filled /></el-icon>
              </el-tooltip>
            </div>
            <div class="card-amount green">{{ formatAmount(statisticsData.total_loan_amount) }}¥</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card" shadow="never">
            <div class="card-title">
              <span>自营放贷</span>
              <el-tooltip content="自营放贷总额" placement="top">
                <el-icon><i-ep-question-filled /></el-icon>
              </el-tooltip>
            </div>
            <div class="card-amount">{{ formatAmount(statisticsData.self_loan_amount) }}¥</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card" shadow="never">
            <div class="card-title">
              <span>助贷</span>
              <el-tooltip content="助贷总额" placement="top">
                <el-icon><i-ep-question-filled /></el-icon>
              </el-tooltip>
            </div>
            <div class="card-amount">{{ formatAmount(statisticsData.assist_loan_amount) }}¥</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第二行卡片 -->
      <el-row :gutter="20" class="mt-20">
        <el-col :span="8">
          <el-card class="data-card" shadow="never">
            <div class="card-title">
              <span>本月放款总额</span>
              <el-tooltip content="当月累计放款金额" placement="top">
                <el-icon><i-ep-question-filled /></el-icon>
              </el-tooltip>
            </div>
            <div class="card-amount">{{ formatAmount(statisticsData.month_loan_amount) }}¥</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card" shadow="never">
            <div class="card-title">
              <span>本月自营放贷</span>
              <el-tooltip content="当月自营放贷总额" placement="top">
                <el-icon><i-ep-question-filled /></el-icon>
              </el-tooltip>
            </div>
            <div class="card-amount">{{ formatAmount(statisticsData.month_self_loan_amount) }}¥</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card" shadow="never">
            <div class="card-title">
              <span>本月助贷</span>
              <el-tooltip content="当月助贷总额" placement="top">
                <el-icon><i-ep-question-filled /></el-icon>
              </el-tooltip>
            </div>
            <div class="card-amount">{{ formatAmount(statisticsData.month_assist_loan_amount) }}¥</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第三行卡片 -->
      <el-row :gutter="20" class="mt-20">
        <el-col :span="8">
          <el-card class="data-card" shadow="never">
            <div class="card-title">
              <span>今日放款统计</span>
              <el-tooltip content="当日放款总额" placement="top">
                <el-icon><i-ep-question-filled /></el-icon>
              </el-tooltip>
            </div>
            <div class="card-amount">{{ formatAmount(statisticsData.today_loan_amount) }}¥</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card" shadow="never">
            <div class="card-title">
              <span>合计待出款</span>
              <el-tooltip content="待出款总额" placement="top">
                <el-icon><i-ep-question-filled /></el-icon>
              </el-tooltip>
            </div>
            <div class="card-amount">{{ formatAmount(statisticsData.total_pending_loan) }}¥</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card" shadow="never">
            <div class="card-title">
              <span>合计待回款</span>
              <el-tooltip content="待回款总额" placement="top">
                <el-icon><i-ep-question-filled /></el-icon>
              </el-tooltip>
            </div>
            <div class="card-amount">{{ formatAmount(statisticsData.total_pending_repay) }}¥</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第四行卡片 -->
      <el-row :gutter="20" class="mt-20">
        <el-col :span="8">
          <el-card class="data-card" shadow="never" @click="goToFeeSettlement">
            <div class="card-title">
              <span>结算总额</span>
              <el-tooltip content="已结算总金额，点击查看详情" placement="top">
                <el-icon><i-ep-question-filled /></el-icon>
              </el-tooltip>
            </div>
            <div class="card-amount">{{ formatAmount(statisticsData.total_settlement) }}¥</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card" shadow="never">
            <div class="card-title">
              <span>经纪人总数</span>
              <el-tooltip content="系统注册经纪人数量" placement="top">
                <el-icon><i-ep-question-filled /></el-icon>
              </el-tooltip>
            </div>
            <div class="card-amount">{{ statisticsData.total_brokers }}人</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <!-- 留空或添加其他指标 -->
        </el-col>
      </el-row>
    </div>

    <!-- 图表部分 -->
    <div class="charts-section mt-20">
      <!-- 图表筛选条件 -->
      <el-card shadow="never" class="filter-card">
        <div class="filter-container">
          <span class="filter-label">统计时间范围：</span>
          <div style="width: 300px;">
            <el-date-picker v-model="dateRange" type="daterange" unlink-panels range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="shortcuts" @change="handleDateChange" />
          </div>
        </div>
      </el-card>

      <el-row :gutter="20" class="mt-20">
        <el-col :span="12">
          <el-card class="chart-card" shadow="never" v-loading="chartLoading">
            <div class="card-header">
              <div class="title">放款统计</div>
            </div>
            <div id="loanChart" class="chart-container" ref="chartRef"></div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="chart-card" shadow="never" v-loading="chartLoading">
            <div class="card-header">
              <div class="title">投放完成率</div>
            </div>
            <div class="completion-rate">
              <el-progress type="dashboard" :percentage="Math.round(chartData.investment_rate * 100)" :width="180"
                :stroke-width="10" :format="() => investmentRateText">
              </el-progress>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="chart-card" shadow="never" v-loading="chartLoading">
            <div class="card-header">
              <div class="title">收费完成率</div>
            </div>
            <div class="completion-rate">
              <el-progress type="dashboard" :percentage="Math.round(chartData.charge_rate * 100)" :width="180"
                :stroke-width="10" :format="() => chargeRateText">
              </el-progress>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped lang="scss">
.statistics-overview {
  .page-actions {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
  }

  .filter-card {
    .filter-container {
      display: flex;
      align-items: center;

      .filter-label {
        margin-right: 10px;
        font-weight: bold;
      }
    }
  }

  .mt-20 {
    margin-top: 20px;
  }

  .data-card {
    height: 120px; // 固定卡片高度
    display: flex;
    flex-direction: column;

    .card-title {
      display: flex;
      align-items: center;
      color: #606266;
      font-size: 14px;
      margin-bottom: 10px;

      .el-icon {
        margin-left: 5px;
        font-size: 16px;
        color: #909399;
      }
    }

    .card-amount {
      font-size: 24px;
      font-weight: bold;
      margin: 10px 0;

      &.green {
        color: #67C23A;
      }
    }

    .card-action {
      display: flex;
      justify-content: flex-start;
      margin-top: auto; // 将按钮推到底部
      margin-bottom: 5px;
    }

    &.clickable {
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        transform: translateY(-2px);
      }
    }
  }

  .chart-card {
    height: 400px;

    .card-header {
      margin-bottom: 15px;

      .title {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .chart-container {
      height: 350px;
      width: 100%;
      overflow: visible;
      margin: 10px 0;
    }

    .completion-rate {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 300px;

      :deep(.el-progress__text) {
        font-size: 24px !important;
        font-weight: bold;
        color: #409EFF;
      }

      :deep(.el-progress--success .el-progress__text) {
        color: #67C23A;
      }
    }
  }
}
</style>